﻿using Wen.GrpcService.Entity;
using Wen.GrpcService.Helps;

namespace Wen.GrpcService.InternalService;

public class UserService(IFreeSql fsql)
{
    /// <summary>
    /// 获取用户
    /// </summary>
    /// <param name="userName"></param>
    /// <returns></returns>
    public SysUser? GetUserByUserName(string? userName)
    {
        return fsql.Queryable<SysUser>().Where(t => t.UserName == userName).First();
    }
    /// <summary>
    /// 验证用户密码
    /// </summary>
    /// <param name="username"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    public bool VerifyLogin(string username, string password)
    {
        var user = GetUserByUserName(username);
        if (user == null || user.PasswordSalt is null) { return false; }
        return user.Password == AesRsaHelp.ComputeHash(password, user.PasswordSalt);
    }
    /// <summary>
    /// 保存用户
    /// </summary>
    /// <param name="username"></param>
    /// <param name="password"></param>
    /// <param name="displayName"></param>
    /// <param name="description"></param>
    public void SaveUser(string username, string password, string displayName, string description)
    {
        var user = GetUserByUserName(username);
        var salt = AesRsaHelp.GenerateSalt();
        var pad = AesRsaHelp.ComputeHash(password, salt);
        if (user == null)
        {
            user = new SysUser()
            {
                UserName = username,
                Password = pad,
                DisplayName = displayName,
                Description = description,
                PasswordSalt = salt
            };
            fsql.Insert(user).ExecuteAffrows();
        }
        else
        {
            user.Password = pad;
            user.DisplayName = displayName;
            user.Description = description;
            user.PasswordSalt = salt;
            fsql.Update<SysUser>(user).ExecuteAffrows();
        }
    }
    /// <summary>
    /// 重置密码
    /// </summary>
    /// <param name="username"></param>
    /// <param name="password"></param>
    public void ResetPassword(string username, string password)
    {
        var user = fsql.Select<SysUser>().Where(a => a.UserName == username).First();  //此时快照 item

        if (user == null) return;

        var salt = AesRsaHelp.GenerateSalt();
        user.Password = AesRsaHelp.ComputeHash(password, salt);
        user.PasswordSalt = salt;
        fsql.Update<SysUser>().SetSource(user).ExecuteAffrows();
    }
    /// <summary>
    /// 插入
    /// </summary>
    /// <param name="user"></param>
    /// <returns></returns>
    public bool Insert(SysUser user)
    {
        user.UserName = user.UserName?.ToLower();
        if (user.UserName is null || fsql.Queryable<SysUser>().Where(t => t.UserName == user.UserName).Any())
        {
            return false;
        }
        else
        {
            fsql.Insert(user).ExecuteAffrows();
            return true;
        }
    }
}
